#include <type.h>

int strcmp(const char *d, const char *s)
{
	int i = 0;
	while(d[i] == s[i] && d[i] != 0)
		i++;

	return d[i] - s[i];
}

char *strcpy(char *d, const char *s)
{
	int i = 0;
	while((d[i] = s[i]) != 0)
		i++;

	return d;
}

int strlen(const char *s)
{
	int i = 0;
	while(s[i] != '\0')
		i++;
	return i;
}

char *strchr(const char *s, int ch)
{
	int i = 0;
	while(s[i] != '\0') {
		if(s[i] == ch)
			return &s[i];
		i++;
	}
	return NULL;
}

char *strrchr(const char *s, int ch)
{
	int i = 0;
	char *p = NULL;
	while(s[i] != '\0') {
		if(s[i] == ch)
			p = &s[i];
		i++;
	}
	return p;
}

void hex2str(char *str, u32_t n)
{
	int k, i;

	str[0] = '0';
	str[1] = 'x';
	str[10] = '\0';
	for(i = 9; i > 1; i--) {
		k = n % 16;
		str[i] = k < 10 ? k + '0' : k + 'A' - 10;
		n /= 16;
	}
}

void dec2str(char *str, int n)
{
	int i = 18, flag = 0;
	char tmp[20];

	if(n == 0) {
		tmp[i--] = '0';
		goto out;
	}

	if(n < 0) {
		n = -n;
		flag = 1;
	}

	while(n) {
		tmp[i--] = n % 10 + '0';
		n /= 10;
	}

	if(flag)
		tmp[i--] = '-';

out:
	tmp[19] = '\0';
	strcpy(str, tmp + i + 1);
}

int vsprintf(char *buf, const char *fmt, u32_t* argv)
{
	char *p = buf;
	char tmp[20];

	while(*fmt) {
		if(*fmt != '%') {
			*p++ = *fmt++;
			continue;
		}

		switch(*(++fmt)) {
		case 'x':
			hex2str(tmp, *argv++);
			strcpy(p, tmp);
			p += strlen(tmp);
			break;
		case 'd':
			dec2str(tmp, *argv++);
			strcpy(p, tmp);
			p += strlen(tmp);
			break;
		case 'c':
			*(p++) = (char)(*argv++);
			break;
		case 's':
			strcpy(p, (char *)(*argv));
			p += strlen((char *)(*argv++));
			break;
		default:
			*p++ = '%';
			*p++ = *fmt;
		}
		fmt++;
	}
	*p++ = '\0';

	return p - buf;
}
